#-*- coding: UTF-8 -*- 

import xml.etree.ElementTree as ET
import StringIO

def __get_widget_attr(node):
    attrib = node.attrib
    widget = {}
    text = attrib['text']
    skip = True
    try:
        int(attrib['text'])
    except:
        skip = False
    if attrib['text'] != '' and skip == False:
        widget['class'] = attrib['class']
        widget['text'] = attrib['text']
        widget['priority'] = len(attrib['text'])
        
        return widget
    else:
        children_node = node.getchildren()
        if len(children_node) == 0:
            return
        for child in children_node:
            attrib = child.attrib
            skip = True
            try:
                int(attrib['text'])
            except:
                skip = False
            if attrib['text'] != '' and skip == False:
                widget['class'] = attrib['class']
                widget['text'] = attrib['text']
                widget['priority'] = len(attrib['text'])
                return widget
    return None


def __walk_clicked_widget(node, widgets, package_name):
    attrib = node.attrib
    if attrib.has_key('package'):
        if attrib['package'] == package_name:
            if attrib['enabled'] == 'true':
                if attrib['clickable'] == 'true' or attrib['checkable'] == 'true':
                    widget = __get_widget_attr(node)
                    if widget:
                        widgets['clickable'].append(widget)
                        return
                elif attrib['scrollable'] == 'true':
                    widgets['scrollable'] = True                   
    
    children_node = node.getchildren()
    if len(children_node) == 0:
        return
    for child in children_node:
        __walk_clicked_widget(child, widgets, package_name)
    return

def parse_file(file_name, package_name):
    widgets = []
    root = ET.parse(file_name).getroot()
    __walk_clicked_widget(root, widgets, package_name)

    return widgets

def parse(str, package_name):
    widgets = {}
    widgets['clickable'] = []
    widgets['checkable'] = []
    widgets['scrollable'] = False
    #root = ET.fromstring(str)
    utf8_parser = ET.XMLParser(encoding='utf-8')
    tree = ET.parse(StringIO.StringIO(str.encode('utf-8')), parser=utf8_parser)
    root=tree.getroot()
    __walk_clicked_widget(root, widgets, package_name)

    widgets['clickable'] = sorted(widgets['clickable'], key=lambda widget: widget['priority'])
    return widgets
    
    
if __name__ == '__main__':
    R = parse_file('settings.xml', 'com.android.settings')
    for x in R:
        print x
    pass